//
//  XMHomeDetailViewController.m
//  XMJJ_zml
//
//  Created by 杨何华 on 2025/5/12.
//

#import "XMHomeDetailViewController.h"
#import "ProductBannerView.h"
#import "SDCycleScrollView.h"
#import "OrderSectionCell.h"
#import "DescriptionSectionCell.h"
#import "ReviewSectionCell.h"
#import "ReviewCustomCell.h"
#import "PersonCustomCell.h"
#import "CustomTabView.h"
#import "XMCommentViewController.h"
#import "PersonMainPageViewController.h"
#import "XMAddressViewController.h"
#import "CustomNavigationBar.h"
#import "XMDetailModel.h"
#import "LocationDecoder.h"
#import <CoreLocation/CoreLocation.h>
// 定义分区类型
typedef NS_ENUM(NSInteger, ProductDetailSectionType) {
    ProductDetailSectionTypeBanner = 0,    // 轮播图和价格
    ProductDetailSectionTypeOrder,         // 订单区
    ProductDetailSectionTypeDescription,   // 服务描述
    ProductDetailSectionTypeReviews,       // 评价区
    ProductDetailSectionTypePerson,        // 个人主页
    ProductDetailSectionTypeCount         // 分区总数
    
};


@interface XMHomeDetailViewController ()<UITableViewDelegate,UITableViewDataSource,SDCycleScrollViewDelegate,ReviewCustomCellDelegate,PersonCustomCellDelegate,CustomTabViewCellDelegate,CLLocationManagerDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSArray *imageUrls;      // 轮播图URL数组
@property (nonatomic, strong) NSString *price;         // 价格
@property (nonatomic, strong) NSString *description1;   // 服务描述
@property (nonatomic, strong) NSArray *reviews;        // 评价数据
@property (nonatomic, strong) ProductBannerView *bannerView;
@property (nonatomic, assign) BOOL isDescriptionExpanded;

@property (nonatomic, strong) CustomNavigationBar * customNav;
@property (nonatomic, strong) XMDetailModel * xmDetailModel;
@property (nonatomic, strong) NSMutableArray * list;

@property (nonatomic, strong) CLLocationManager *locationManager;

@end

@implementation XMHomeDetailViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self hideNavigationBar:NO animated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    // 准备数据
    [self.navigationController setHidesBottomBarWhenPushed:YES];
    self.hideNavigationBar = NO;
    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    self.list = [NSMutableArray array];
    NSString *imageUrl = @"https://picsum.photos/600/300";
    NSString *price = @"¥1,299.00";
    _isDescriptionExpanded = true;
    NSString *description1 = @"这是一款高品质的电子产品，拥有出色的性能和时尚的设计。采用最新技术，为您带来卓越的使用体验。无论是工作还是娱乐，它都是您的理想选择。它都是您的理想选择它都是您的理想选择它都是您的理想选择它都是您的理想选择它都是您的理想选择它都是您的理想选择它都是您的理想选择它都是您的理想选择它都是您的理想选择它都是您的理想选择它都是您的理想选择它都是您的理想选择它都是您的理想选择";
    self.description1 =  description1;
       // 计算Banner高度
    CGFloat bannerHeight = [ProductBannerView calculateHeightForWidth:self.view.bounds.size.width
                                                          description:description1];
       
    // 创建Banner视图
    _bannerView = [[ProductBannerView alloc] initWithFrame:CGRectMake(0, 100, self.view.bounds.size.width, bannerHeight - 10)];
    // 设置数据
    [_bannerView setupWithImageUrl:imageUrl
                             price:price
                       description:description1
                  placeholderImage:[UIImage imageNamed:@"placeholder"]];
    
    _bannerView.userInteractionEnabled = YES;
    [self setupTableView];
    [self.tableView setTableHeaderView:_bannerView];
    
    CustomTabView * customTabView = [[CustomTabView alloc]initWithFrame:CGRectMake(0, kScreentHeight - kNavagationBarH, kScreenWidth, kTabBarH)];
    customTabView.delegate = self;
    [self.view addSubview:customTabView];
    [self getRecommendFunciton];
    
    
    
    CGFloat statusBarHeight = [UIApplication sharedApplication].statusBarFrame.size.height;
    self.customNav = [[CustomNavigationBar alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width,  statusBarHeight + 25)];
    self.customNav.title = @"自定义导航栏";
    self.customNav.backAction = ^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.navigationController popViewControllerAnimated:YES];
        });
    };
//      [self.customNav setIsHiddenOnButton:NO];
       // 添加到视图
//       [self.view addSubview:self.customNav];
//       self.hidesBottomBarWhenPushed = YES;
}

//收藏
- (void)favoriteClickAction:(UIButton *)sender {
    NSString * interface = collectionService;
    if([sender.currentTitle isEqualToString:@"取消收藏"]){
        interface = collectionService;
    }else {
        interface = cancelCollectionService;
     }
    MJWeakSelf;
    NSMutableDictionary * mutableDict = @{@"sessionId":self.serviceId}.mutableCopy;
    [_Network getDataWithPath:[NSString stringWithFormat:@"%@%@", HttpInterface, interface]
                   parameters:mutableDict
                    needToken:NO
                      headers:nil
                      success:^(id  _Nonnull responseObject) {
        XMDetailModel * detilModel = [XMDetailModel yy_modelWithJSON:responseObject];
//          NSDictionary * resultDic = responseObject;
//          NSArray * data = [resultDic objectForKey:@"data"];
 
          NSLog(@"%@",detilModel);
         } failure:^(NSError * _Nonnull error) {
             if(error.code == 401){
                 [MBProgressHUD showError:error.localizedDescription];
                 
            }
       }];
}

//查看
- (void)chatClickAction:(NSInteger)tag {
    
}

- (void)goAddresssAction:(NSInteger)tag {
    switch (tag) {
        case 1:
        {
            XMAddressViewController * detailVc = [XMAddressViewController new];
            [self.navigationController pushViewController:detailVc animated:YES];
        }
            break;
        case 2:
        {
            
        }
            break;
        case 3:
        {
            
        }
            break;
        default:
            break;
    }
}

- (void)getRecommendFunciton {
        
       NSMutableDictionary * mutableDict = @{@"serviceId":self.serviceId}.mutableCopy;
       [[XMNetwork shareInstance]getDataWithPath:[NSString stringWithFormat:@"%@%@",HttpInterface,getServiceDetail] parameters:mutableDict needToken:NO headers:nil success:^(id  _Nonnull responseObject) {
//          NSDictionary * resultDic = responseObject;
           NSDictionary * jsonData =  [responseObject objectForKey:@"data"];
           XMDetailModel * detilModel = [XMDetailModel yy_modelWithJSON:jsonData];
           NSArray *pointArray = [detilModel.addrPoint componentsSeparatedByString:@","];
 
           // 1. 直接解码已知经纬度
             CLLocation * location = [[CLLocation alloc] initWithLatitude:[pointArray.firstObject longLongValue] longitude:[pointArray.lastObject longLongValue]]; // 北京坐标
             [[LocationDecoder sharedDecoder] reverseGeocodeLocation:location completion:^(NSDictionary *addressInfo, NSError *error) {
                 if (error) {
                     NSLog(@"解码失败: %@", error.localizedDescription);
                     return;
                 }
                 
                 NSLog(@"解码结果:");
                 NSLog(@"国家: %@", addressInfo[@"country"]);
                 NSLog(@"城市: %@", addressInfo[@"city"]);
                 NSLog(@"详细地址: %@", addressInfo[@"name"]);
             }];
             
             // 2. 获取当前位置并解码
             [[LocationDecoder sharedDecoder] getCurrentLocationWithCompletion:^(NSDictionary *addressInfo, NSError *error) {
                 if (!error) {
                     NSLog(@"当前位置: %@", addressInfo[@"name"]);
                 }
             }];
           
          NSLog(@"%@",detilModel);
          [self->_bannerView setupWithImageUrl:detilModel.coverImageUrl
                                   price:detilModel.totalPrice
                             description:detilModel.title
                        placeholderImage:[UIImage imageNamed:@"placeholder"]];
           [self.list addObject:detilModel];
           [self.list addObject:detilModel];
           [self.list addObject:detilModel];

           [self.tableView reloadData];
         } failure:^(NSError * _Nonnull error) {
           NSLog(@"%@",error.description);
          [MBProgressHUD showError:error.description];
         }];
    
 
}
-(void)bannerTapped:(UITapGestureRecognizer *)tap {
    
}
- (void)setupTableView {
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreentHeight - kTabBarH - 20) style:UITableViewStyleGrouped];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.backgroundColor = [UIColor colorWithRed:0.96 green:0.96 blue:0.96 alpha:1.0];
    _tableView.estimatedRowHeight = 100;
    _tableView.rowHeight = UITableViewAutomaticDimension;
    [self.view addSubview:_tableView];
    
     _tableView.sectionHeaderHeight = 4;
     _tableView.sectionFooterHeight = 4;
    // 注册单元格
    [_tableView registerClass:[OrderSectionCell class] forCellReuseIdentifier:@"OrderSectionCell"];
    [_tableView registerClass:[DescriptionSectionCell class] forCellReuseIdentifier:@"DescriptionSectionCell"];
    [_tableView registerClass:[ReviewCustomCell class] forCellReuseIdentifier:@"ReviewSectionCell"];
    [_tableView registerClass:[PersonCustomCell class] forCellReuseIdentifier:[PersonCustomCell reuseIdentifier]];
}

#pragma mark - UITableViewDelegate & UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return ProductDetailSectionTypeCount;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    switch (section) {
        case ProductDetailSectionTypeOrder:
            return 3;
        case ProductDetailSectionTypeDescription:
            return 1;
        case ProductDetailSectionTypeReviews:
            return 1;
        case ProductDetailSectionTypePerson:
            return 1;
        default:
            return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    switch (indexPath.section) {
        case ProductDetailSectionTypeOrder: {
            OrderSectionCell *cell = [tableView dequeueReusableCellWithIdentifier:@"OrderSectionCell" forIndexPath:indexPath];
            if(self.list.count > 0){
                XMDetailModel * deil =  self.list[indexPath.row];
                [cell setupData:deil];
            }
            return cell;
        }
            
        case ProductDetailSectionTypeDescription: {
            DescriptionSectionCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DescriptionSectionCell" forIndexPath:indexPath];
            if(self.list.count > 0){
                XMDetailModel * deil =  self.list[indexPath.row];
                cell.descriptionText = deil.desc;
            }
             cell.isExpanded = _isDescriptionExpanded; // 使用类变量记录展开状态
             cell.expandCallback = ^(BOOL isExpanded) {
                self->_isDescriptionExpanded = isExpanded;
                
                // 更新单元格高度
                [tableView beginUpdates];
                [tableView endUpdates];
            };
            
            return cell;
          }
            
        case ProductDetailSectionTypeReviews: {
            ReviewCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ReviewSectionCell" forIndexPath:indexPath];
            [cell setupWithAvatarUrl:@"https://picsum.photos/600/300" userName:@"1111" rating:1 reviewText:@"1123" dateString:@"123123" photoUrls:[NSArray arrayWithObjects:@"https://picsum.photos/600/300",@"https://picsum.photos/600/300",@"https://picsum.photos/600/300", nil] placeholderImage:[UIImage imageNamed:@"location"]];
            cell.delegate = self;
            return cell;
        }
        case ProductDetailSectionTypePerson: {
            PersonCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:[PersonCustomCell reuseIdentifier] forIndexPath:indexPath];
            cell.delegate = self;
            return cell;
        }
            
        default:
            return [[UITableViewCell alloc] init];
    }
}

// 打印位置信息
- (void)printPlacemarkInfo:(CLPlacemark *)placemark {
    NSLog(@"解码结果:");
    NSLog(@"经纬度: %f, %f", placemark.location.coordinate.latitude, placemark.location.coordinate.longitude);
    NSLog(@"国家: %@", placemark.country);
    NSLog(@"省份: %@", placemark.administrativeArea);
    NSLog(@"城市: %@", placemark.locality);
    NSLog(@"区县: %@", placemark.subLocality);
    NSLog(@"街道: %@", placemark.thoroughfare);
    NSLog(@"门牌号: %@", placemark.subThoroughfare);
    NSLog(@"邮政编码: %@", placemark.postalCode);
    NSLog(@"完整地址: %@", placemark.name);
 }

-(void)goCommentAction:(ReviewCustomCell *)obj
{
    XMCommentViewController * detailVc = [XMCommentViewController new];
    [self.navigationController pushViewController:detailVc animated:YES];
}
-(void)goPersonMainPageAction:(PersonCustomCell *)obj
{
    PersonMainPageViewController * detailVc = [PersonMainPageViewController new];
    [self.navigationController pushViewController:detailVc animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    switch (indexPath.section) {
        case ProductDetailSectionTypeOrder:
            return 50; // 订单区域固定高度
        case ProductDetailSectionTypeDescription:
            return [DescriptionSectionCell calculateHeightForText:self.description1 width:tableView.bounds.size.width isExpanded:true];
        case ProductDetailSectionTypeReviews:
            return [ReviewCustomCell calculateHeightForReviewText:@"1123" photoCount:3 width:100] + 100;
        case ProductDetailSectionTypePerson:
            return  60;
        default:
            return 0;
    }
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark - SDCycleScrollViewDelegate

- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index {
    NSLog(@"点击了第 %ld 张轮播图", (long)index);
    // 处理轮播图点击事件
}
@end
